<%@page language="java" contentType="text/html;charset=UTF-8" %>
<%@page import="java.util.*"%>
<%@page import="weaver.file.FileUpload"%>
<%@page import="weaver.general.Util"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="java.net.URLDecoder"%>
<%@page import="java.net.URLEncoder"%>
<%@page import="weaver.hrm.*" %>
<%@ page import="weaver.systeminfo.*" %>
<%@page import="weaver.general.Util" %>
<%@page import="java.sql.Timestamp" %>
<%@page import="weaver.conn.ConnStatement" %>
<%@page import="weaver.conn.RecordSet" %>
<%@page import="weaver.cowork.*" %>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="weaver.hrm.resource.ResourceComInfo" %>
<%@page import="weaver.hrm.company.DepartmentComInfo" %>
<%@page import="weaver.docs.docs.DocImageManager" %>
<%@page import="weaver.mobile.plugin.ecology.service.HrmResourceService" %>
<%@page import="weaver.general.BaseBean"%>
<%@page import="weaver.crm.customer.CustomerShareUtil"%>
<%@page import="weaver.general.TimeUtil"%>
<%@page import="com.weaver.formmodel.util.DateHelper"%>
<%@page import="weaver.conn.RecordSetTrans"%>
<%@page import="COM.rsa.jsafe.cw"%>
<%@page import="net.sf.json.JSONArray"%>

<jsp:useBean id="CoworkItemMarkOperation" class="weaver.cowork.CoworkItemMarkOperation" scope="page" />
<jsp:useBean id="CoworkService" class="weaver.mobile.plugin.ecology.service.CoworkService" scope="page" />
<jsp:useBean id="CoworkShareManager" class="weaver.cowork.CoworkShareManager" scope="page" />
<jsp:useBean id="CoTypeComInfo" class="weaver.cowork.CoTypeComInfo" scope="page" />
<jsp:useBean id="CoworkTransMethod" class="weaver.general.CoworkTransMethod" scope="page" />
<jsp:useBean id="CoworkDao" class="weaver.cowork.CoworkDAO" scope="page"/>

<jsp:useBean id="RecordSet" class="weaver.conn.RecordSet" scope="page" />
<jsp:useBean id="ResourceComInfo" class="weaver.hrm.resource.ResourceComInfo" scope="page" />
<jsp:useBean id="csm" class="weaver.cowork.CoworkShareManager" scope="page" />

<%!
public String showRelatedaccList(ArrayList relatedaccList,User user,int coworkid) throws Exception{
	    RecordSet recordSet=new RecordSet();
	    DocImageManager docImageManager=new DocImageManager(); 
	    String accStr="";
		for(int i=0;i<relatedaccList.size();i++){  
			recordSet.executeSql("select id,docsubject,accessorycount from docdetail where id="+relatedaccList.get(i));
            int linknum=-1;
          	if(recordSet.next()){
          		linknum++;
          		String showid = Util.null2String(recordSet.getString(1)) ;
              String tempshowname= Util.toScreen(recordSet.getString(2),user.getLanguage()) ;
              int accessoryCount=recordSet.getInt(3);

              docImageManager.resetParameter();
              docImageManager.setDocid(Integer.parseInt(showid));
              docImageManager.selectDocImageInfo();

              String docImagefileid = "";
              long docImagefileSize = 0;
              String docImagefilename = "";
              String fileExtendName = "";
              int versionId = 0;

              if(docImageManager.next()){
                //DocImageManager会得到doc第一个附件的最新版本
                docImagefileid = docImageManager.getImagefileid();
                docImagefileSize = docImageManager.getImageFileSize(Util.getIntValue(docImagefileid));
                docImagefilename = docImageManager.getImagefilename();
                fileExtendName = docImagefilename.substring(docImagefilename.lastIndexOf(".")+1).toLowerCase();
                versionId = docImageManager.getVersionId();
              }
              if(accessoryCount>1){
                fileExtendName ="htm"; 
              }

             //String imgSrc=AttachFileUtil.getImgStrbyExtendName(fileExtendName,20);
             //accStr=accStr+imgSrc;
             accStr+= "<div class='fileDiv'>";
             accStr=accStr+"<a href='javascript:void(0)' isCanDown='1'  onclick=\"downloads('"+docImagefileid+"',"+coworkid+",'"+docImagefilename+"');return false;\" class='relatedLink'>"+docImagefilename+"</a>";
             if(accessoryCount==1){
            	 accStr=accStr+"&nbsp;&nbsp;<a href='javascript:void(0)' isCanDown='1' onclick=\"downloads('"+docImagefileid+"',"+coworkid+",'"+docImagefilename+"');return false;\" class='relatedLink'>"+SystemEnv.getHtmlLabelName(258,user.getLanguage())+"("+(docImagefileSize/1000.0)+"K)</a><br>";
             }
             accStr+= "</div>";
		}
		}
		return accStr;
	}	
 %>
<%
out.clearBuffer();
request.setCharacterEncoding("UTF-8");
FileUpload fu=new FileUpload(request);
HrmResourceService hrs = new HrmResourceService();
int userid = Util.getIntValue(fu.getParameter("userid"));
User user = hrs.getUserById(userid);
if(user==null) {
	Map result = new HashMap();
	//未登录或登录超时
	result.put("error", "200001");
	
	JSONObject jo = JSONObject.fromObject(result);
	out.println(jo);
	
	return;
}
int coworkid = Util.getIntValue(fu.getParameter("coworkid"));
String operation = Util.null2String(fu.getParameter("operation"));
int replayid = Util.getIntValue(fu.getParameter("replayid"), 0);
int pageIndex = Util.getIntValue(fu.getParameter("pageindex"), 1);
int pageSize = Util.getIntValue(fu.getParameter("pagesize"), 10);
String sessionkey = Util.null2String(fu.getParameter("sessionkey"));
String remark = Util.null2String(fu.getParameter("remark"));
remark = URLDecoder.decode(remark,"utf-8");

String module = Util.null2String((String)request.getParameter("module"));
String scope = Util.null2String((String)request.getParameter("scope"));
String keyword = Util.null2String(fu.getParameter("keyword"));
keyword = URLDecoder.decode(keyword, "utf-8");

String ctype = Util.null2String(fu.getParameter("ctype"));
if("".equals(ctype)){
	ctype = "all";
}
String labelid = Util.null2String(fu.getParameter("labelid"));
String important = Util.null2String(fu.getParameter("important"));
Map result = new HashMap();
if("getCoworkDetail".equals(operation)) {
	String join = "success_jsonpCallback(";
	JSONObject jsonobj = new JSONObject();
	boolean canView=CoworkShareManager.isCanView(""+coworkid,""+userid,"all");
	if (coworkid > 0 && canView) {
		CoworkDAO dao = new CoworkDAO(coworkid);
		CoworkItemsVO vo = dao.getCoworkItemsVO();
		String cname = Util.null2String(vo.getName());                 //协作名称
		String ccreater = Util.null2String(vo.getCreater());           //协作创建人
		String cprincipal=Util.null2String(vo.getPrincipal());         //协作负责人
		String ctypeid=Util.null2String(vo.getTypeid());               //所属协作区
		String cbegindate = Util.null2String(vo.getBegindate());       //开始日期
		String cbeingtime = Util.null2String(vo.getBeingtime());       //开始时间      
		String cenddate = Util.null2String(vo.getEnddate());           //结束日期
		String cendtime = Util.null2String(vo.getEndtime());           //结束时间
		String cremark = Util.null2String(vo.getRemark()).trim();	   //详细描述
		String capprovalAtatus=vo.getApprovalAtatus();                 //审批状态，待审批
		//添加查看者记录
		String sql="select id from cowork_read where coworkid="+coworkid+" and userid="+userid;
		RecordSet rs = new RecordSet();
		rs.execute(sql);  
		if(!rs.next()){
			sql="insert into cowork_read(coworkid,userid) values("+coworkid+","+userid+")";
			rs.execute(sql);
		}
	
		//添加查看日志
		dao.addCoworkLog(coworkid,2,userid,fu);
		
		ResourceComInfo rci = new ResourceComInfo();
/* 		join += "name:\""+ cname+"\",creater:\""+rci.getResourcename(ccreater)+"\",principal:\""+rci.getResourcename(cprincipal)+"\",typeid:\""+ctypeid+"\",begindate:\""+cbegindate+
			"\",beingtime:\""+cbeingtime+"\",enddate:\""+cenddate+"\",endtime:\""+cendtime+"\",remark:\""+cremark+"\",approvalAtatus:\""+capprovalAtatus+"\"";
 */		
 		jsonobj.put("name", cname);
 		jsonobj.put("creater", rci.getResourcename(ccreater));
 		jsonobj.put("principal", rci.getResourcename(cprincipal));
 		jsonobj.put("typeid", ctypeid);
 		jsonobj.put("begindate", cbegindate);
 		jsonobj.put("beingtime", cbeingtime);
 		jsonobj.put("enddate", cenddate);
 		jsonobj.put("endtime", cendtime);
 		jsonobj.put("remark", cremark);
 		jsonobj.put("approvalAtatus", capprovalAtatus);
	}
	join +=jsonobj.toString()+")";
	out.println(join);
} else if("getCoworkList".equals(operation)) {
	String condition = "";
	if(keyword!=null && !"".equals(keyword)) {
		condition = (" (name like '%"+keyword+"%') ");
	}
	
		RecordSet recordSet = new RecordSet();
		List list = new ArrayList();
		int count = 0;
		int pageCount = 0;
		int isHavePre = 0;
		int isHaveNext = 0;
		
		if(user != null) {

			int departmentid=user.getUserDepartment();   //用户所属部门
			int subCompanyid=user.getUserSubCompany1();  //用户所属分部
			String seclevel=user.getSeclevel();          //用于安全等级
			
			
			
			weaver.cowork.CoworkService coworkService=new weaver.cowork.CoworkService();
			String baseSql="("+
				" select t1.id,t1.name,t1.status,t1.typeid,t1.creater,t1.principal,t1.begindate,t1.enddate,t1.replyNum,t1.readNum,t1.lastdiscussant,t1.lastupdatedate,t1.lastupdatetime,t1.isApproval,t1.approvalAtatus,t1.isTop,t2.cotypeid,"+
				" case when  t3.sourceid is not null then 1 when t2.cotypeid is not null then 0 end as jointype,"+
				" case when  t4.coworkid is not null then 0 else 1 end as isnew,"+
				" case when  t5.coworkid is not null then 1 else 0 end as important,"+
				" case when  t6.coworkid is not null then 1 else 0 end as ishidden"+
				(ctype.equals("label")?" ,case when  t7.coworkid is not null then 1 else 0 end as islabel":"")+
				" from cowork_items  t1 left join "+
				//关注的协作
				" ( "+coworkService.getManagerShareSql(userid+"")+" )  t2 on t1.typeid=t2.cotypeid left join "+ 
		        //直接参与的协作
				" ("+coworkService.getPartnerShareSql(userid+"")+")  t3 on t3.sourceid=t1.id"+
		        //阅读|重要|隐藏
				" left join (select distinct coworkid,userid from cowork_read where userid="+userid+")  t4 on t1.id=t4.coworkid"+       //阅读状态
				" left join (select distinct coworkid,userid from cowork_important where userid="+userid+" )  t5 on t1.id=t5.coworkid"+ //重要性
				" left join (select distinct coworkid,userid from cowork_hidden where userid="+userid+" )  t6 on t1.id=t6.coworkid"+    //是否隐藏
				(ctype.equals("label")?" left join (select distinct coworkid from cowork_item_label where labelid="+labelid+") t7 on t1.id=t7.coworkid":"")+ 
				" ) t ";
			
			//暂时只能查看已经审批过的协作
			baseSql=baseSql+" where status =1 and (approvalAtatus=0 or (approvalAtatus=1 and (creater="+userid+" or principal="+userid+" or cotypeid is not null))) and jointype is not null ";
			
			if(!"".equals(condition)) {
					baseSql += " and " + condition + " ";
			}
			
			
			if("unread".equals(ctype)){
				baseSql=baseSql+" and isnew=1 and ishidden<>1";
			}else if("important".equals(ctype)){
				baseSql=baseSql+" and important=1 and ishidden<>1";
			}else if("hidden".equals(ctype)){
				baseSql=baseSql+" and ishidden=1";
			}else if("all".equals(ctype)){
				baseSql=baseSql+" and ishidden<>1";
			}else if("label".equals(ctype)){
	        	baseSql=baseSql+" and ishidden<>1 and islabel=1";
	        }else if("typePlate".equals(ctype)){
	        	baseSql = baseSql+" and typeid = (select name from cowork_label where id = "+labelid+")";
	        }
			String countSql = " select count(*) as c from " + baseSql;
			RecordSet rs = new RecordSet();
			rs.executeSql(countSql);
			if(rs.next())
				count = rs.getInt("c");
			
			if(pageIndex <=0 ) pageIndex = 1;
			if(pageSize <=0 ) pageSize = 10;
			
			if (count <= 0) pageCount = 0;
			pageCount = count / pageSize + ((count % pageSize > 0)?1:0);
			
			isHaveNext = (pageIndex + 1 <= pageCount)?1:0;

			isHavePre = (pageIndex - 1 >= 1)?1:0;
			
			String splitSql = "";
			if(recordSet.getDBType().equals("oracle")){
				splitSql = "select *  from "+baseSql+" order by jointype desc,isnew desc,important desc,id desc";
				
				splitSql = "select t1.*,rownum rn from (" + splitSql + ") t1 where rownum <= " + (pageIndex * pageSize);
				splitSql = "select t2.* from (" + splitSql + ") t2 where rn > " + ((pageIndex-1) * pageSize);
			}else{
				if(pageIndex>1) {
					int topSize = pageSize;
					if(pageSize * pageIndex > count) {
						topSize = count - (pageSize * (pageIndex - 1));
					}
					splitSql = "select top "+(pageIndex * pageSize)+" *  from "+baseSql+" order by jointype desc,isnew desc,important desc,id desc";
					
					splitSql = "select top " + topSize +" t1.* from (" + splitSql + ") t1 order by t1.jointype asc,t1.isnew asc,t1.important asc,t1.id asc";
					splitSql = "select top " + topSize +" t2.* from (" + splitSql + ") t2 order by t2.jointype desc,t2.isnew desc,t2.important desc,t2.id desc";
				} else {
					splitSql = "select top "+pageSize+" *  from "+baseSql+" order by jointype desc,isnew desc,important desc,id desc";
				}
			}
			ConnStatement statement=new ConnStatement();
			try {
				if(pageIndex <= pageCount) {
					ResourceComInfo rci = new ResourceComInfo();
					statement.setStatementSql(splitSql);
					statement.executeQuery();
					
					while(statement.next()){
						int cid=statement.getInt("id");
						Map map = new HashMap();
						
						map.put("id", ""+cid);
						map.put("isnew", Util.null2o(statement.getString("isnew")));
						map.put("subject", Util.null2String(statement.getString("name")));
						map.put("important", Util.null2o(statement.getString("important")));
						map.put("approvalAtatus", Util.null2o(statement.getString("approvalAtatus")));
						boolean canEdit=CoworkShareManager.isCanEdit(""+cid,""+userid,"all");
						map.put("canEdit", canEdit);
						
						List label = new ArrayList();
						rs.execute("select t2.id,t2.name,t2.labelColor,t2.textColor from cowork_item_label t1,cowork_label t2 where t2.userid='"+userid+"' and t1.coworkid='"+cid+"' and t1.Labelid=t2.id");
				    	while(rs.next()){
				    		Map lab = new HashMap();
				    		
				    		lab.put("id", rs.getString("id"));
				    		lab.put("name", rs.getString("name"));
				    		lab.put("labelColor", rs.getString("labelColor"));
				    		lab.put("textColor", rs.getString("textColor"));
				    		
				    		label.add(lab);
				    	}
				    	
				    	//最新评论
				    	String lastdisstr="无";
				    	rs.execute("select * from cowork_discuss where coworkid="+cid+" order by id desc");
				    	if(rs.next()){
				    		String discussant = Util.null2String(rs.getString("discussant"));
							String dimg = rci.getMessagerUrls(discussant);//照片
							String dname = rci.getResourcename(discussant);//姓名
							String createdate = Util.null2String(rs.getString("createdate"));  //最新回复日期
							String createtime = Util.null2String(rs.getString("createtime"));  //最新回复时间
							String posttime = createdate+"&nbsp;"+createtime;//最新发表时间
				    		//lastdisstr = dname+"<img src='"+dimg+"'>于"+posttime+"回复";
				    		lastdisstr = dname+"于"+posttime+"回复";
				    	}
				    	map.put("lastdisstr", lastdisstr);
						
						list.add(map);
				    }
				}
				result.put("datas",list);
				result.put("totalSize",count+"");
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				statement.close();
			}
		} else {
			result.put("error", "200001");
		}
		if(count == 0){
			out.print("{\"totalSize\":0, \"datas\":[]}");
			return;
		}
		JSONObject json = JSONObject.fromObject(result);
		out.print(json.toString());
}else if("getDetalilCoworkList".equals(operation)){
		Map<String, Object> detail = new HashMap<String, Object>();
		int count = 0;
		int pageCount = 0;
		int isHavePre = 0;
		int isHaveNext = 0;
		
		List coworks = new ArrayList();
		
		if(pageSize <= 0) {
			pageSize = 20;
		}
		if(pageIndex <= 0) pageIndex = 1;
		
		try {
			if(user != null) {
				boolean canView = csm.isCanView(""+coworkid,""+userid,"all");
				if(canView) {
					detail.put("status", "1");
					
					ResourceComInfo rci = new ResourceComInfo();
					DepartmentComInfo dci = new DepartmentComInfo();
					CoworkDAO dao = new CoworkDAO(coworkid);
					count =dao.getDiscussVOListCount("");
					
					pageCount = count / pageSize;
					if(count - pageCount * pageSize > 0) pageCount = pageCount + 1;
					
					isHaveNext = (pageIndex + 1 <= pageCount)?1:0;
					isHavePre = (pageIndex - 1 >= 1)?1:0;
					
					if(pageIndex <= pageCount) {
						List list = dao.getDiscussVOList(pageIndex, pageSize, "");
						
						if(list != null && list.size() > 0) {
							for(int k=0;k<list.size();k++){
								CoworkDiscussVO vo = (CoworkDiscussVO)list.get(k);
								
								Map<String, Object> cowork = new HashMap<String, Object>();
								cowork.put("id", vo.getId());
								cowork.put("coworkid", vo.getCoworkid());
								String discussant = Util.null2String(vo.getDiscussant());
								cowork.put("image", rci.getMessagerUrls(discussant));//照片
								cowork.put("floorNum", vo.getFloorNum());//楼号
								cowork.put("name", rci.getResourcename(discussant));//姓名
								cowork.put("deptname", dci.getDeptnames(rci.getDepartmentID(discussant)));//部门
								String createdate = Util.null2String(vo.getCreatedate());  //创建日期
								String createtime = Util.null2String(vo.getCreatetime());  //创建时间
								cowork.put("posttime", CoworkTransMethod.getFormateDate(createdate,createtime));//发表时间
								String remark2 = Util.null2String(vo.getRemark());//回复内容
								cowork.put("remark2html", Util.StringReplace(remark2.trim(),"\r\n",""));
								cowork.put("relatedacc", showRelatedaccList(vo.getRelatedaccList(),user,Util.getIntValue(vo.getId())));
								String replaystr = "";
								String rid=Util.null2String(vo.getReplayid());
								if(!"".equals(rid) && !"0".equals(rid)) {
									CoworkDiscussVO discussvo=dao.getCoworkDiscussVO(rid);
									if(discussvo!=null){
										replaystr = "<div class='commentReply'>";
										replaystr += "引用 "+discussvo.getFloorNum()+"# "+rci.getResourcename(discussvo.getDiscussant())+" "+discussvo.getCreatedate()+" "+discussvo.getCreatetime()+"";
										replaystr += "<div class='commentReplyContent'>"+Util.StringReplace(discussvo.getRemark().trim(),"\n","<br>")+"</div>";
										replaystr += "<div class='commentReplyRelate'>"+showRelatedaccList(discussvo.getRelatedaccList(),user,Util.getIntValue(discussvo.getId()))+"</div>";
										replaystr += "</div>";
									}
								}
								cowork.put("replay", replaystr);
								//评论
								List commentList=dao.getCommentList(vo.getId());
								String commentstr ="";
								if(commentList.size()>0){
									commentstr ="<div class='commentContainerTitle'>评论</div><div class='commentReply2'><ul class='reply'>";
									for(int j=0;j<commentList.size();j++){
										CoworkDiscussVO commentvo=(CoworkDiscussVO)commentList.get(j);
					       		     	String commentdiscussant=commentvo.getDiscussant();
					       		     	String commentdiscussid=commentvo.getId();
					       		     	String commentuserid=commentvo.getCommentuserid();
					       		     	String comemntremark=commentvo.getRemark();
					       		     	commentstr+="<li>"+rci.getResourcename(commentdiscussant)+" "+CoworkTransMethod.getFormateDate(commentvo.getCreatedate(),commentvo.getCreatetime())+"<br/>"+comemntremark+"</li>";
									}
									commentstr+="</ul></div>";
								}
								cowork.put("commentstr", commentstr);
								coworks.add(cowork);
							}
						}
					}
				} else {
					detail.put("status", "0");
				}
			} else {
				detail.put("error", "no data");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		detail.put("datas",coworks);
		detail.put("totalSize",count+"");
			
		if(count == 0){
			out.print("{\"totalSize\":0, \"datas\":[]}");
			return;
		}
		JSONObject json = JSONObject.fromObject(detail);
		out.print(json.toString());
}else if("getrelatedmeCoworkList".equals(operation)){
		Map<String, Object> detail = new HashMap<String, Object>();
		int count = 0;
		int pageCount = 0;
		int isHavePre = 0;
		int isHaveNext = 0;
		
		List coworks = new ArrayList();
		
		if(pageSize <= 0) {
			pageSize = 20;
		}
		if(pageIndex <= 0) pageIndex = 1;
		
		try {
			if(user != null) {
				boolean canView = csm.isCanView(""+coworkid,""+userid,"all");
				if(canView) {
					detail.put("status", "1");
					
					ResourceComInfo rci = new ResourceComInfo();
					DepartmentComInfo dci = new DepartmentComInfo();
					CoworkDAO dao = new CoworkDAO(coworkid);
					//count =dao.getDiscussVOListCount("");
					count =dao.getDiscussReplayListCount(""+userid,""+coworkid,"");
					
					pageCount = count / pageSize;
					if(count - pageCount * pageSize > 0) pageCount = pageCount + 1;
					
					isHaveNext = (pageIndex + 1 <= pageCount)?1:0;
					isHavePre = (pageIndex - 1 >= 1)?1:0;
					
					if(pageIndex <= pageCount) {
						List list = dao.getDiscussReplayList(pageIndex, pageSize, ""+userid,""+coworkid,"");
						if(list != null && list.size() > 0) {
							for(int k=0;k<list.size();k++){
							
								CoworkDiscussVO vo = (CoworkDiscussVO)list.get(k);
								
								Map<String, Object> cowork = new HashMap<String, Object>();
								cowork.put("id", vo.getId());
								cowork.put("coworkid", vo.getCoworkid());
								String discussant = Util.null2String(vo.getDiscussant());
								cowork.put("image", rci.getMessagerUrls(discussant));//照片
								cowork.put("floorNum", vo.getFloorNum());//楼号
								cowork.put("name", rci.getResourcename(discussant));//姓名
								cowork.put("deptname", dci.getDeptnames(rci.getDepartmentID(discussant)));//部门
								String createdate = Util.null2String(vo.getCreatedate());  //创建日期
								String createtime = Util.null2String(vo.getCreatetime());  //创建时间
								cowork.put("posttime", CoworkTransMethod.getFormateDate(createdate,createtime));//发表时间
								String remark2 = Util.null2String(vo.getRemark());//回复内容
								cowork.put("remark2html", Util.StringReplace(remark2.trim(),"\r\n",""));
								cowork.put("relatedacc", showRelatedaccList(vo.getRelatedaccList(),user,Util.getIntValue(vo.getId())));
								String replaystr = "";
								String rid=Util.null2String(vo.getReplayid());
								if(!"".equals(rid) && !"0".equals(rid)) {
									CoworkDiscussVO discussvo=dao.getCoworkDiscussVO(rid);
									if(discussvo!=null){
										replaystr = "<div class='commentReply'>";
										replaystr += "引用 "+discussvo.getFloorNum()+"# "+rci.getResourcename(discussvo.getDiscussant())+" "+discussvo.getCreatedate()+" "+discussvo.getCreatetime()+"";
										replaystr += "<div class='commentReplyContent'>"+Util.StringReplace(discussvo.getRemark().trim(),"\n","<br>")+"</div>";
										replaystr += "<div class='commentReplyRelate'>"+showRelatedaccList(discussvo.getRelatedaccList(),user,Util.getIntValue(discussvo.getId()))+"</div>";
										replaystr += "</div>";
									}
								}
								cowork.put("replay", replaystr);
								//评论
								List commentList=dao.getCommentList(vo.getId());
								String commentstr ="";
								if(commentList.size()>0){
									commentstr ="<div class='commentReply2'><ul class='reply'>";
									for(int j=0;j<commentList.size();j++){
										CoworkDiscussVO commentvo=(CoworkDiscussVO)commentList.get(j);
					       		     	String commentdiscussant=commentvo.getDiscussant();
					       		     	String commentdiscussid=commentvo.getId();
					       		     	String commentuserid=commentvo.getCommentuserid();
					       		     	String comemntremark=commentvo.getRemark();
					       		     	commentstr+="<li>"+rci.getResourcename(commentdiscussant)+"&nbsp;&nbsp;"+CoworkTransMethod.getFormateDate(commentvo.getCreatedate(),commentvo.getCreatetime())+"<br>"+comemntremark+"</li>";
									}
									commentstr+="</ul></div>";
								}
								cowork.put("commentstr", commentstr);
								coworks.add(cowork);
							}
						}
					}
				} else {
					detail.put("status", "0");
				}
			} else {
				detail.put("error", "no data");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		detail.put("datas",coworks);
		detail.put("totalSize",count+"");
			
		if(count == 0){
			out.print("{\"totalSize\":0, \"datas\":[]}");
			return;
		}
		JSONObject json = JSONObject.fromObject(detail);
		out.print(json.toString());
}else if("getjoinCowork".equals(operation)){
		JSONObject jsonobj = new JSONObject();
		ResourceComInfo resourceComInfo = new ResourceComInfo();
		
		String aliststr = "";
		List alist=csm.getShareConditionStrList(""+coworkid);
		for(int i=0;i<alist.size();i++){
 			HashMap hm=(HashMap)alist.get(i);
			String type=Util.null2String(hm.get("type"));
			int typelabel=Util.getIntValue((String)hm.get("typeName"));	
			aliststr+="<li>"+SystemEnv.getHtmlLabelName(typelabel, user.getLanguage())+"&nbsp;&nbsp;&nbsp;"+hm.get("contentName");
			if(!type.equals("1")){
				aliststr+= "&nbsp;&nbsp;&nbsp;"+hm.get("seclevel")+"-"+hm.get("seclevelMax");
			}  	   
			aliststr+="</li>";
		}
		if(!"".equals(aliststr)){
			aliststr = "<ul class='ajoin'><li>参与条件：</li>"+aliststr+"</ul>";
		}
		jsonobj.put("ajoin", aliststr);
		
		String parteridsstr = "";
		List parterids=csm.getShareList("parter",""+coworkid);
		String pstr = "";
		for(int i=0;i<parterids.size()&&i<10;i++){
 			String resourceid=(String)parterids.get(i);       
			pstr += Util.toScreen(resourceComInfo.getResourcename((String)resourceid),user.getLanguage())+"&nbsp;";
		}
		if(parterids.size()>10){
			pstr += "<a href=\"javascript:void(0);\" onclick=\"showall('"+userid+"','"+coworkid+"',1)\" >全部</a>";
		}
		List  typemanagerids=csm.getShareList("typemanager",""+coworkid);
		String tstr = "";
		for(int i=0;i<typemanagerids.size()&&i<10;i++){
 			String resourceid=(String)typemanagerids.get(i);       
			tstr += Util.toScreen(resourceComInfo.getResourcename((String)resourceid),user.getLanguage())+"&nbsp;";
		}
		if(typemanagerids.size()>10){
			tstr += "...";
		}
		parteridsstr+="<ul class='parterul'><li>参与人员：</li><li>"+SystemEnv.getHtmlLabelName(17689, user.getLanguage())+"&nbsp;&nbsp;&nbsp;<div id='showall1' style='display:inline;'>"+pstr+"</div></li><li>"+SystemEnv.getHtmlLabelName(25472, user.getLanguage())+"&nbsp;&nbsp;&nbsp;<div id='showall1' style='display:inline;'>"+tstr+"</div></li></ul>";		
		jsonobj.put("parteridsstr", parteridsstr);
		
		String noReadidsstr = "";
		String nstr="";
		List noReadids=csm.getNoreadUseridList(""+coworkid);
		for(int i=0;i<noReadids.size()&&i<10;i++){
			String resourceid=(String)noReadids.get(i);
			nstr += Util.toScreen(resourceComInfo.getResourcename((String)resourceid),user.getLanguage())+"&nbsp;";
		}
		if(noReadids.size()>10){
			nstr += "<a href=\"javascript:void(0);\" onclick=\"showall('"+userid+"','"+coworkid+"',3)\" >全部</a>";
		}
		noReadidsstr+="<ul class='noReadidsstrul'><li>未查看者：</li><li>未查看者&nbsp;&nbsp;&nbsp;<div id='showall3' style='display:inline;'>"+nstr+"</div></li></ul>";
		jsonobj.put("noReadidsstr", noReadidsstr);
		
		out.print(jsonobj.toString());
}else if("alljoinCowork".equals(operation)){
		String showtype= Util.null2String(fu.getParameter("showtype"));
		JSONObject jsonobj = new JSONObject();
		ResourceComInfo resourceComInfo = new ResourceComInfo();
		if("1".equals(showtype)){
			List parterids=csm.getShareList("parter",""+coworkid);
			String pstr = "";
			for(int i=0;i<parterids.size();i++){
	 			String resourceid=(String)parterids.get(i);       
				pstr += Util.toScreen(resourceComInfo.getResourcename((String)resourceid),user.getLanguage())+"&nbsp;";
			}
			jsonobj.put("showall1", pstr);
		}else if("2".equals(showtype)){
			String tstr = "";
			List  typemanagerids=csm.getShareList("typemanager",""+coworkid);
			for(int i=0;i<typemanagerids.size();i++){
	 			String resourceid=(String)typemanagerids.get(i);       
				tstr += Util.toScreen(resourceComInfo.getResourcename((String)resourceid),user.getLanguage())+"&nbsp;";
			}
			jsonobj.put("showall2", tstr);
		}else{
			String nstr="";
			List noReadids=csm.getNoreadUseridList(""+coworkid);
			for(int i=0;i<noReadids.size();i++){
				String resourceid=(String)noReadids.get(i);
				nstr += Util.toScreen(resourceComInfo.getResourcename((String)resourceid),user.getLanguage())+"&nbsp;";
			}
			jsonobj.put("showall3", nstr);
		}
		out.print(jsonobj.toString());
}else if("getlabellist".equals(operation)) {
	String json = "{";
	String labelstr = "[";
	List labelList=CoworkItemMarkOperation.getLabelList(userid+"","all");          //标签列表
	for(int i=0;i<labelList.size();i++){ 
         CoworkLabelVO labelVO=(CoworkLabelVO)labelList.get(i);
         String isUsed=labelVO.getIsUsed();
         if(isUsed.equals("0")) continue;
         String id=labelVO.getId();
         String labelType=labelVO.getLabelType();
         String labelName=labelVO.getName();
         if(labelName.equals("17694"))  continue;//过滤掉协作区标签
         
         if(labelType.equals("label")){
      	   labelName=labelVO.getName();
         }else if(labelType.equals("typePlate")){
        	   labelName = CoTypeComInfo.getCoTypename(labelVO.getName());
         }else{
      	   labelName=SystemEnv.getHtmlLabelName(Util.getIntValue(labelVO.getName()),user.getLanguage());
         }
         //labelstr +="<label ontap='openDetail(\"mobilemode:refreshList:687::ctype="+labelType+"&label="+id+":listStatusChanged\",null,{\"refreshedCallbackParamData\":"+labelName+"});'>"+labelName+"</label>";
  	  	labelstr+="{\"id\":\""+id+"\",\"labelType\":\""+labelType+"\",\"labelName\":\""+labelName+"\"},";
    }
    if(labelstr.length()>1){
    	labelstr = labelstr.substring(0, labelstr.length()-1);  
    }   
    labelstr = labelstr+"]";
    json += "\"labelstr\":"+labelstr+"}";
	out.print(json);
}else if("markimportant".equals(operation)) {
	ArrayList coworkidList = Util.TokenizerString(""+coworkid,",");
	CoworkDAO dao=new CoworkDAO();
	String flag="";
	for(int i=0;i < coworkidList.size(); i++){
			String cid = (String)coworkidList.get(i);
			flag+= CoworkItemMarkOperation.markItemAsType(user.getUID()+"",cid,important)+",";
			//添加已读记录
			if(important.equals("read"))
				dao.addCoworkLog(coworkid,2,user.getUID(),fu);
		}	
	result.put("flag", flag);
	JSONObject json = JSONObject.fromObject(result);
	out.print(json.toString());	
}else if("markread".equals(operation)) {
	String read = Util.null2String(fu.getParameter("read"));
	ArrayList coworkidList = Util.TokenizerString(""+coworkid,",");
	CoworkDAO dao=new CoworkDAO();
	String flag="";
	for(int i=0;i < coworkidList.size(); i++){
		String cid = (String)coworkidList.get(i);
		flag+= CoworkItemMarkOperation.markItemAsType(user.getUID()+"",cid,read)+",";
		//添加已读记录
		if(read.equals("read"))
			dao.addCoworkLog(coworkid,2,user.getUID(),fu);
	}	
	result.put("flag", flag);
	JSONObject json = JSONObject.fromObject(result);
	out.print(json.toString());	
}else if("showReplay".equals(operation)) {
	JSONObject json = new JSONObject();
	try{
		String extendField=Util.null2String(fu.getParameter("extendField"));
		String content=Util.null2String(fu.getParameter("content"));
		json.put("extendField", extendField);
		json.put("content", content);
		json.put("status", "1");
	}catch(Exception ex){
		ex.printStackTrace();
		result.put("status", "0");
		String errMsg = Util.null2String(ex.getMessage());
		errMsg = URLEncoder.encode(errMsg, "UTF-8");
		errMsg = errMsg.replaceAll("\\+","%20");
		json.put("errMsg", errMsg);
	}
	out.print("<script type=\"text/javascript\">parent.Mobile_NS.operationResponse("+json.toString()+");</script>");

}
else if("important".equals(operation)) {
	result = CoworkService.markCoworkItemAsType(coworkid, "important", user);
	JSONObject json = JSONObject.fromObject(result);
	out.print(json.toString());
} else if("normal".equals(operation)) {
	result = CoworkService.markCoworkItemAsType(coworkid, "normal", user);
	JSONObject json = JSONObject.fromObject(result);
	out.print(json.toString());
}else if("doremark".equals(operation)||"subcontent".equals(operation)){
	JSONObject json = new JSONObject();
	
	weaver.cowork.CoworkService coService = new weaver.cowork.CoworkService();
	int accessorynum = Util.getIntValue(fu.getParameter("accessory_num"),0);
	int deleteField_idnum = Util.getIntValue(fu.getParameter("field_idnum"),0);
	String id = Util.null2String(fu.getParameter("id"));      //协作id
	String did = "";//回复ID                            
	String replyType = "";                     //回复类型
	String from = "cowork";//用来表示从哪个页面进入的，从协作区进入from="cowork"，从其他地方进入from="other"
	String extendField=Util.null2String(fu.getParameter("extendField"));
	String parm[] = extendField.split("_");
	if(parm.length>2){
		did =  parm[0];
		id = parm[1];
		if("2".equals(parm[2])){
			replyType = "comment";
		}
	}
	String name = Util.fromScreen(fu.getParameter("name"),user.getLanguage());
	BaseBean baseBean = new BaseBean();
	String typeid = Util.fromScreen(fu.getParameter("typeid"),user.getLanguage());
	int isApply = Util.getIntValue(fu.getParameter("isApply"),0);
	String levelvalue = Util.null2String(fu.getParameter("levelvalue"),"0");
	String creater = Util.fromScreen(fu.getParameter("creater"),user.getLanguage());
	String coworkers = Util.fromScreen(fu.getParameter("coworkers"),user.getLanguage());
	String begindate = Util.fromScreen(fu.getParameter("begindate"),user.getLanguage());
	String beingtime = Util.fromScreen(fu.getParameter("beingtime"),user.getLanguage());
	String enddate = Util.fromScreen(fu.getParameter("enddate"),user.getLanguage());
	String endtime = Util.fromScreen(fu.getParameter("endtime"),user.getLanguage());
	String relatedprj = Util.fromScreen(fu.getParameter("relatedprj"),user.getLanguage()); //相关项目任务
	String relatedcus = Util.fromScreen(fu.getParameter("relatedcus"),user.getLanguage()); //相关客户
	relatedcus=CustomerShareUtil.customerRightFilter(""+user.getUID(),relatedcus);
	String relatedwf = Util.fromScreen(fu.getParameter("relatedwf"),user.getLanguage());   //相关流程
	String relateddoc = Util.fromScreen(fu.getParameter("relateddoc"),user.getLanguage()); //相关文档
	if("0".equals(relateddoc)) relateddoc="";
	String relatedacc =Util.fromScreen(fu.getParameter("relatedacc"),user.getLanguage());  //相关附件

	String projectIDs = Util.null2String(fu.getParameter("projectIDs"));//td11838          //相关项目

	String principal = Util.null2String(fu.getParameter("txtPrincipal"));                  //协作负责人



	String commentuserid = Util.null2String(fu.getParameter("commentuserid"));             //被评论人id

	String topdiscussid = Util.null2String(fu.getParameter("topdiscussid"));               //被评论的留言id

	String approvalAtatus = Util.null2String(fu.getParameter("approvalAtatus")); //审批状态 1 为待审批 
	String isApproval = "";
	String isAnonymous = ""; //是否匿名


	String createdate =TimeUtil.getCurrentDateString();     //当前日期
	String createtime =TimeUtil.getOnlyCurrentTimeString(); //当前时间

	String status ="1";
	char flag = 2;
	String Proc="";
	String userId =""+user.getUID();
	boolean isoracle = (RecordSet.getDBType()).equals("oracle");
	String disType=Util.null2String((String)session.getAttribute("disType")); //协作讨论显示方式，tree为树形
	int floorNum=0;
	if(operation.equals("doremark")){ //回复讨论

			try{
				String content=Util.null2String(fu.getParameter("content"));
				
				CoworkDAO dao = new CoworkDAO(Util.getIntValue(id));
				CoworkItemsVO vo = dao.getCoworkItemsVO();
				String cname = Util.null2String(vo.getName());                 //协作名称
				String ccreater = Util.null2String(vo.getCreater());           //协作创建人
				principal=Util.null2String(vo.getPrincipal());         		   //协作负责人
				String ctypeid=Util.null2String(vo.getTypeid());               //所属协作区
				String cbegindate = Util.null2String(vo.getBegindate());       //开始日期
				String cbeingtime = Util.null2String(vo.getBeingtime());       //开始时间      
				String cenddate = Util.null2String(vo.getEnddate());           //结束日期
				String cendtime = Util.null2String(vo.getEndtime());           //结束时间
				String capprovalAtatus=vo.getApprovalAtatus();                 //审批状态，待审批
				isAnonymous = vo.getIsAnonymous();
				isAnonymous=isAnonymous.equals("")?"0":isAnonymous;
				isApproval = vo.getIsApproval();
				
				CoworkDiscussVO cvo  = dao.getCoworkDiscussVO(did);
				topdiscussid = did;               //被评论的留言id
				commentuserid = cvo.getDiscussant();             //被评论人id
				if(!"".equals(relatedacc)){
			   		csm.addCoworkDocShare(userId,relatedacc,typeid,id,principal); //添加附件共享
				}
		    
			    replayid= Util.getIntValue(did,0);
			    int commentid=replayid;
			    String sql="";
			    if(!replyType.equals("comment")){ //引用产生新的楼层
				    //获取当前最大楼数
				    sql="select max(floorNum) as floorNum  from cowork_discuss where coworkid="+id;
				    RecordSet.execute(sql);
				    if(RecordSet.next())
				    	floorNum=RecordSet.getInt("floorNum");
				    if(floorNum==-1)
						floorNum=0;
				    floorNum=floorNum+1;
			    }else
			    	replayid=0;
				
			    //添加讨论
				Proc=id+flag+userid+flag+createdate+flag+createtime+flag+content+flag+relatedprj+flag+relatedcus+flag+relatedwf+flag+relateddoc+flag+relatedacc+flag+projectIDs+flag+floorNum+flag+replayid;
				
			    RecordSet.executeProc("cowork_discuss_insert",Proc);
			    
			    RecordSet.executeSql("select max(id) as maxid from cowork_discuss where coworkid="+id+" and discussant="+userid);
				String currentid="0";
				String discussid="0";
				if(RecordSet.next()){
					currentid=RecordSet.getString("maxid");
				}
				
				RecordSet.executeSql("update cowork_discuss set TOPDISCUSSID=0,COMMENTID=0,COMMENTUSERID=0,ISTOP=0,APPROVALATATUS=0,ISANONYMOUS=0,ISDEL=0 where id="+currentid);
				
				ArrayList reminderidList=new ArrayList();
				
			    if(replyType.equals("comment")){ //
			    	RecordSet.executeSql("update cowork_discuss set commentid="+commentid+",topdiscussid="+topdiscussid+",commentuserid="+commentuserid+" where id="+currentid);
			    	
			    	sql="select discussant from cowork_discuss where topdiscussid="+topdiscussid+" or id="+topdiscussid;
			    }else{
			    	//引用、评论时计算回复数
			    	RecordSet.executeSql("update cowork_items set replyNum=replyNum+1,lastupdatedate='"+createdate+"',lastupdatetime='"+createtime+"',lastdiscussant="+(isAnonymous.equals("1")?"0":userId)+" where id="+id);
			    	
			    	sql="select discussant from cowork_discuss where id="+replayid;
			    }
			    
			    RecordSet.execute(sql);
			    //提醒评论相关人
			    while(RecordSet.next()){
					String reminderid=RecordSet.getString("discussant");
					if(!reminderidList.contains(reminderid)&&!reminderid.equals(userid)){
						reminderidList.add(reminderid);
					}
				}
			    
			    for(int i=0;i<reminderidList.size();i++){
			    	discussid=replyType.equals("comment")?topdiscussid:currentid;
			    	sql="select id from cowork_remind where reminderid="+reminderidList.get(i)+" and discussid="+discussid;
			    	RecordSet.execute(sql);
			    	if(RecordSet.next()){
			    		sql="update cowork_remind set createdate='"+createdate+"',createtime='"+createtime+"' where reminderid="+reminderidList.get(i)+" and discussid="+discussid;
			    	}else{
				    	sql="insert into cowork_remind(reminderid,discussid,coworkid,createdate,createtime) values"+
				    		"("+reminderidList.get(i)+","+discussid+","+id+",'"+createdate+"','"+createtime+"')";
			    	}	
			    	RecordSet.execute(sql);
			    }
			    RecordSet.executeSql("update cowork_discuss set approvalAtatus="+isApproval+",isAnonymous="+isAnonymous+" where id="+currentid);
				
			  	//提醒协作负责人
			    if(!reminderidList.contains(principal)&&!principal.equals(userid)){
					reminderidList.add(principal);
				}
			    
				//协作提醒
				coService.addSysRemind(id,userId,reminderidList);
				
				if(replyType.equals("comment")){
					//只清除评论相关人的阅读记录
					for(int i=0;i<reminderidList.size();i++){
						
						coService.delReadByUserid(id,(String)reminderidList.get(i));
					}
				}else{
					//所有看过协作的参与者，都会记录到cowork_read，协作更新后就要删除cowork_read中的已经查看者
					coService.delRead(id);
					//将当前回复者添加到已读者中
					coService.addRead(id,userId);
				}
				json.put("status", "1");
			}catch(Exception ex){
				ex.printStackTrace();
				json.put("status", "0");
				String errMsg = Util.null2String(ex.getMessage());
				errMsg = URLEncoder.encode(errMsg, "UTF-8");
				errMsg = errMsg.replaceAll("\\+","%20");
				json.put("errMsg", errMsg);
			}
			out.print(json.toString());
	}else if(operation.equals("subcontent")){
	 //回复
			try{
				String content=Util.null2String(fu.getParameter("content"));
				
				if(!"".equals(relatedacc)){
			   		csm.addCoworkDocShare(userId,relatedacc,typeid,id,principal); //添加附件共享
				}
		    
			    replayid= Util.getIntValue(did,0);
			    int commentid=replayid;
			    String sql="";
			    if(!replyType.equals("comment")){ //引用产生新的楼层
				    //获取当前最大楼数
				    sql="select max(floorNum) as floorNum  from cowork_discuss where coworkid="+id;
				    RecordSet.execute(sql);
				    if(RecordSet.next())
				    	floorNum=RecordSet.getInt("floorNum");
				    if(floorNum==-1)
						floorNum=0;
				    floorNum=floorNum+1;
			    }else
			    	replayid=0;
				
			    //添加讨论
				Proc=id+flag+userid+flag+createdate+flag+createtime+flag+content+flag+relatedprj+flag+relatedcus+flag+relatedwf+flag+relateddoc+flag+relatedacc+flag+projectIDs+flag+floorNum+flag+replayid;
				
			    RecordSet.executeProc("cowork_discuss_insert",Proc);
			    
			    RecordSet.executeSql("select max(id) as maxid from cowork_discuss where coworkid="+id+" and discussant="+userid);
				String currentid="0";
				String discussid="0";
				if(RecordSet.next()){
					currentid=RecordSet.getString("maxid");
				}
				
				RecordSet.executeSql("update cowork_discuss set TOPDISCUSSID=0,COMMENTID=0,COMMENTUSERID=0,ISTOP=0,APPROVALATATUS=0,ISANONYMOUS=0,ISDEL=0 where id="+currentid);
				
				ArrayList reminderidList=new ArrayList();
				
			    if(replyType.equals("comment")){ //
			    	RecordSet.executeSql("update cowork_discuss set commentid="+commentid+",topdiscussid="+topdiscussid+",commentuserid="+commentuserid+" where id="+currentid);
			    	
			    	sql="select discussant from cowork_discuss where topdiscussid="+topdiscussid+" or id="+topdiscussid;
			    }else{
			    	//引用、评论时计算回复数
			    	RecordSet.executeSql("update cowork_items set replyNum=replyNum+1,lastupdatedate='"+createdate+"',lastupdatetime='"+createtime+"',lastdiscussant="+(isAnonymous.equals("1")?"0":userId)+" where id="+id);
			    	
			    	sql="select discussant from cowork_discuss where id="+replayid;
			    }
			    
			    RecordSet.execute(sql);
			    //提醒评论相关人
			    while(RecordSet.next()){
					String reminderid=RecordSet.getString("discussant");
					if(!reminderidList.contains(reminderid)&&!reminderid.equals(userid)){
						reminderidList.add(reminderid);
					}
				}
			    
			    for(int i=0;i<reminderidList.size();i++){
			    	discussid=replyType.equals("comment")?topdiscussid:currentid;
			    	sql="select id from cowork_remind where reminderid="+reminderidList.get(i)+" and discussid="+discussid;
			    	RecordSet.execute(sql);
			    	if(RecordSet.next()){
			    		sql="update cowork_remind set createdate='"+createdate+"',createtime='"+createtime+"' where reminderid="+reminderidList.get(i)+" and discussid="+discussid;
			    	}else{
				    	sql="insert into cowork_remind(reminderid,discussid,coworkid,createdate,createtime) values"+
				    		"("+reminderidList.get(i)+","+discussid+","+id+",'"+createdate+"','"+createtime+"')";
			    	}	
			    	RecordSet.execute(sql);
			    }
			    RecordSet.executeSql("update cowork_discuss set approvalAtatus="+isApproval+",isAnonymous="+isAnonymous+" where id="+currentid);
				
			  	//提醒协作负责人
			    if(!reminderidList.contains(principal)&&!principal.equals(userid)){
					reminderidList.add(principal);
				}
			    
				//协作提醒
				coService.addSysRemind(id,userId,reminderidList);
				
				if(replyType.equals("comment")){
					//只清除评论相关人的阅读记录
					for(int i=0;i<reminderidList.size();i++){
						
						coService.delReadByUserid(id,(String)reminderidList.get(i));
					}
				}else{
					//所有看过协作的参与者，都会记录到cowork_read，协作更新后就要删除cowork_read中的已经查看者
					coService.delRead(id);
					//将当前回复者添加到已读者中
					coService.addRead(id,userId);
				}
				json.put("status", "1");
			}catch(Exception ex){
				ex.printStackTrace();
				json.put("status", "0");
				String errMsg = Util.null2String(ex.getMessage());
				errMsg = URLEncoder.encode(errMsg, "UTF-8");
				errMsg = errMsg.replaceAll("\\+","%20");
				json.put("errMsg", errMsg);
			}
			out.print(json.toString());
	}
}else if("addCowork".equals(operation)){
	char flag = 2;
	String name = Util.null2String(fu.getParameter("name"));
	String typeid = Util.null2String(fu.getParameter("typeid")); 
	String isApply = Util.null2String(fu.getParameter("isApply")); 
	String principal = Util.null2String(fu.getParameter("txtPrincipal"));//协作负责人
	String createdate = DateHelper.getCurrentDate();
	String createtime = DateHelper.getCurrentTime();
	String begindate = DateHelper.getCurrentDate();
	String beingtime = "";
	String enddate = TimeUtil.dateAdd(begindate,1);
	String endtime = "";
	String levelvalue = Util.null2String(fu.getParameter("levelvalue"),"0");
	String creater = ""+userid;
	String relatedprj = ""; //相关项目任务
	String relatedcus = ""; //相关客户
	String relatedwf = "";   //相关流程
	String tempdocids = "";
	String status ="1";
	String relatedacc = "";  //相关附件
	String projectIDs = ""; //相关项目
	String isApproval = Util.null2String(fu.getParameter("isApproval"));
	if("".equals(isApproval)){
		isApproval = "0";
	}
	String approvalAtatus = Util.null2String(fu.getParameter("approvalAtatus")); //审批状态 1 为待审批 
	String isAnonymous = Util.null2String(fu.getParameter("isAnonymous")); //是否匿名
	isAnonymous=isAnonymous.equals("")?"0":isAnonymous;
	
	//添加事务控制，创建异常回滚数据
    RecordSetTrans rst=new RecordSetTrans();
	rst.setAutoCommit(false);
	try{
		String Proc=name+flag+typeid+flag+levelvalue+flag+creater+flag+principal+flag+
	          createdate+flag+createtime+flag+begindate+flag+beingtime+flag+enddate+flag+
	          endtime+flag+relatedprj+flag+relatedcus+flag+relatedwf+flag+tempdocids+flag+
	          remark+flag+status+flag+relatedacc+flag+projectIDs+flag+creater;
		 rst.executeProc("cowork_items_insert",Proc);
		
		//获取当前协作id
		 while(rst.next()){
			 coworkid = rst.getInt(1);
		     rst.execute("update cowork_items set isApply = "+isApply+" where id = "+coworkid);
		 }
		 rst.commit();
	}catch(Exception e){
		rst.rollback();
		e.printStackTrace();
	}
	
	
	
	//判断协作是否创建成功不为空表示创建成功
	if(coworkid>0){
		//添加协作参与人共享表	   
		String[] shareids=fu.getParameterValues("tshareid");                            //参与条件id
		String[] types=fu.getParameterValues("tsharetype");                             //参与类型
		String[] contents=fu.getParameterValues("trelatedshareid");                     	    //参与内容
		String[] seclevels=fu.getParameterValues("tseclevel");                          //安全等级
		String[] jobtitlelevels = fu.getParameterValues("tjobtitlelevel");
		String[] jobtitlescopeids = fu.getParameterValues("tjobtitlescopeid");
		if(seclevels == null)seclevels = new String[]{"0"};
		String[] seclevelMaxs=fu.getParameterValues("tseclevelMax");
		if(seclevelMaxs == null)seclevelMaxs = new String[]{"100"};
		RecordSet rs=new RecordSet(); 
		String strSql="";
		
		//插入创建者与负责人为编辑权限
		strSql="insert into coworkshare (sourceid,type,content,seclevel,sharelevel,srcfrom) values ("+coworkid+",1,'"+creater+"',0,2,2)";
		rs.executeSql(strSql);
		//添加负责人
		strSql="insert into coworkshare (sourceid,type,content,seclevel,sharelevel,srcfrom) values ("+coworkid+",1,'"+principal+"',0,2,3)";
		rs.executeSql(strSql);
		
		//插入其它共享条件
		try {
			if(types!=null&&types.length>0) {
				for(int i=0;i<types.length;i++){
					String shareid=Util.null2String(shareids[i]);
					String type=Util.null2String(types[i]);
					String content=Util.null2String(contents[i]);
					String jobtitlelevel="0";
					String jobtitlescopeid=jobtitlescopeids==null?"":Util.null2String(jobtitlescopeids[i]);
					String seclevel = "10";
					String seclevelMax = "100";
					try {
						jobtitlelevel=trim(Util.null2String(jobtitlelevels[i]));
					    seclevel=Math.min(Util.getIntValue(seclevels[i]),Util.getIntValue(seclevelMaxs[i]))+"";
					    seclevelMax=Math.max(Util.getIntValue(seclevels[i]),Util.getIntValue(seclevelMaxs[i]))+"";
					} catch (Exception e) {
					}
					if(!"5".equals(type)&&"".equals(content)) continue; 
					String jobtitleid = "0";
					if(jobtitlelevel == null||"".equals(jobtitlelevel))jobtitlelevel="0";
					if("6".equals(type))jobtitleid = trim(content);
					jobtitlescopeid = ","+trim(jobtitlescopeid)+",";
				    if("2".equals(type)||"3".equals(type)||"4".equals(type)||"1".equals(type))
				    content = ","+trim(content)+",";
					
					strSql="insert into coworkshare (sourceid,type,content,seclevel,seclevelMax,sharelevel,srcfrom,jobtitleid,joblevel,scopeid) values ("+coworkid+","+type+",'"+content+"',"+seclevel+","+seclevelMax+",1,1,'"+jobtitleid+"',"+jobtitlelevel+",'"+jobtitlescopeid+"')";
					rs.executeSql(strSql);
				}
			}
		} catch (Exception e) {
			new BaseBean().writeLog(e);
		}
		
		weaver.cowork.CoworkService coworkService=new weaver.cowork.CoworkService();
		//修改参与人或者添加协作时更新缓存
		CoworkShareManager.deleteCache("parter",""+coworkid);
		
		//将创建者添加到已读
		coworkService.addRead(""+coworkid,""+userid);
		
		//协作创建日志
		CoworkDao.addCoworkLog(coworkid,1,userid,fu);
		RecordSet.execute("update cowork_items set lastupdatedate='"+createdate+"',lastupdatetime='"+createtime+"',isApproval="+isApproval+",isAnonymous="+isAnonymous+",approvalAtatus="+isApproval+",istop=0,readNum=0,replyNum=0 where id="+coworkid);
		//协作提醒
		List parterList=csm.getShareList("parter",""+coworkid);
		
		if(approvalAtatus.equals("1")){
			coworkService.addSysRemind(""+coworkid,""+userid,parterList);
		}
	}
}else if("getCoworkInfo".equals(operation)){
	RecordSet rs = new RecordSet();
	RecordSet rs1 = new RecordSet();
	String sql = "select *,(select lastname from hrmresource where id=a.principal) principalname from cowork_items a where a.id="+coworkid;
	rs.executeSql(sql);
	JSONObject json = new JSONObject();
	String id = "";
	String name = "";
	String typeid = "";
	String principal = "";
	String principalname = "";
	String isApply = "";
	String tremark = "";
	if(rs.next()){
		id = rs.getString("id");
		name = Util.null2String(rs.getString("name"));
		typeid = Util.null2String(rs.getString("typeid"));
		principal = Util.null2String(rs.getString("principal"));
		principalname = Util.null2String(rs.getString("principalname"));
		isApply = Util.null2String(rs.getString("isApply"));
		tremark = Util.null2String(rs.getString("remark"));
	}
	json.put("id",id);
	json.put("name",name);
	json.put("typeid",typeid);
	json.put("principal",principal);
	json.put("principalname",principalname);
	json.put("isApply",isApply);
	json.put("remark",tremark);
	sql = "select * from coworkshare where sourceid="+id+" and srcfrom=1";
	rs.executeSql(sql);
	JSONArray jsonArray = new JSONArray();
	while(rs.next()){
		JSONObject jsonObject = new JSONObject();
		String ttype = Util.null2String(rs.getString("type"));
		String tcontent = Util.null2String(rs.getString("content"));
		jsonObject.put("id",rs.getString("id"));
		jsonObject.put("ttype",ttype);
		jsonObject.put("tcontent",tcontent);
	}
	JSONObject resultJson = new JSONObject();
	resultJson.put("coworkBaseData",json.toString());
	out.print(resultJson.toString());
}
%>
<%!
public String trim(String str) {
	String returnstr="";
	String sz[]=str.split(",");
	for(int i=0;i<sz.length;i++){
		if(!"".equals(sz[i])){//主要用于排查字符串中的多个逗号的情况如：（3，，4，，，6，）
			returnstr+=sz[i]+",";
		}
	}
	int len = returnstr.length();
	int st = 0;
	int off = 0;
	char[] val = returnstr.toCharArray();
	while ((st < len) && (val[off + st] <= ',')) {
	st++;
	}
	while ((st < len) && (val[off + len - 1] <= ',')) {
	len--;
	}
	return ((st > 0) || (len < returnstr.length())) ? returnstr.substring(st, len): returnstr;
}
%>